<template>
  <div class="statistics-container">
    <!-- <div class="notice-module">
      <div class="template-preview">
        <div class="title">通知模板预览：</div>
        <div class="content">【{{ props.position.name }}】，{{ customize }}</div>
      </div>
      <div class="template-edit">
        <el-input v-model="customize" type="textarea" :rows="3" placeholder="请输入自定义通知内容" />
      </div>
    </div> -->
    <div class="action-bar">
      <div class="action-bar-left">
        <el-button type="primary" plain @click="handleReport">查看图表统计与分析</el-button>
        <!-- <el-button type="primary" plain :disabled="!selectedRows.length" @click="handleBatchNotice">结果通知</el-button> -->
      </div>
      <div class="filter-section">
        <el-select v-model="queryData.state" placeholder="状态筛选" clearable @change="getApplicationList">
          <el-option
            v-for="(item, key) in stateMapping"
            :key="key"
            :label="item.label"
            :value="key"
          />
        </el-select>
      </div>
    </div>
    <el-table v-loading="loading" :data="applicationList" style="width: 100%" @selection-change="handleSelectionChange"
      row-key="id" :default-sort="{ prop: 'applyTime', order: 'descending' }">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="申请人" min-width="80" />
      <el-table-column prop="account" label="联系电话" width="120" />
      <el-table-column prop="state" label="审核状态" width="80">
        <template #default="{ row }">
          <el-tag :type="stateMapping[row.state]?.type || 'info'">{{ stateMapping[row.state]?.label || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="noticeState" label="通知状态" width="80">
        <template #default="{ row }">
          <el-tag :type="noticeStateMapping[row.noticeState].type">{{ noticeStateMapping[row.noticeState].label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="applyTime" label="投递时间" width="160">
        <template #default="{ row }">
          {{ dayjs(row.applyTime).format('YYYY-MM-DD HH:mm') }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="{ row }">
          <el-button link type="primary" @click="showDetail(row)">详情</el-button>
          <el-popconfirm
            title="请选择审核结果"
            width="220"
            confirmButtonText="通过"
            cancelButtonText="不通过"
            placement="bottom"
            @confirm="handleAudit(row, true)"
            @cancel="handleAudit(row, false)"
          >
            <template #reference>
              <el-button link type="primary">审核</el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" type="primary" @click="confirm">通过</el-button>
              <el-button size="small" type="danger" @click="cancel">不通过</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="detailVisible" title="简历详情" width="700px" align-center>
      <FormEcho :formData="curFormConfig" :modelValue="curFormResult" height="70vh" :simple="true" />
    </el-dialog>
    <el-dialog v-model="showReport" title="图表统计与分析" width="1200px" align-center>
      <div v-loading="iframeLoading" class="report-iframe-container">
        <iframe :src="reportUrl" frameborder="0" @load="handleIframeLoad"></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable */
import { ref, onMounted } from 'vue'
import { selectListByPostId, noticeRecord } from '@/api/record'
import { selectPaperResult, updatePaperResultState } from '@/api/form'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FormEcho } from '@ruifox-cms/components'
import { encrypt } from '@ruifox-cms/utils'
import dayjs from 'dayjs'

const props = defineProps({
  position: {
    type: Object,
    required: true
  }
})

const stateMapping = {
  0: {label: '待审核', type: 'warning'},
  1: {label: '已通过', type: ''},
  2: {label: '未通过', type: 'danger'}
}
const noticeStateMapping = {
  0: {label: '未通知', type: 'warning'},
  1: {label: '已通知', type: 'success'}
}
const customize = ref('')
// 图表统计与分析
const showReport = ref(false)
const reportUrl = ref('')
const iframeLoading = ref(false)

const handleReport = () => {
  let url = ''
  if (process.env.NODE_ENV === 'development') {
    url = location.protocol + '//' + location.hostname + ':8105/form/manage/statistics?formId=' + encrypt(props.position.paperId)
  } else {
    url = location.origin + '/form/form/manage/statistics?formId=' + encrypt(props.position.paperId)
  }
  if (!reportUrl.value || reportUrl.value !== url) {
    reportUrl.value = url
    iframeLoading.value = true
  }
  showReport.value = true
}

const handleIframeLoad = () => {
  iframeLoading.value = false
}

// 列表数据
const loading = ref(false)
const applicationList = ref([])
const selectedRows = ref([])
const queryData = ref({
  postId: props.position.id,
  state: ''
})
// 获取投递列表
const getApplicationList = async () => {
  loading.value = true
  try {
    const res = await selectListByPostId(queryData.value)
    if (res.code === 20000) {
      applicationList.value = res.data
      console.log(123,res.data)
    }
  } finally {
    loading.value = false
  }
}

// 详情相关
const detailVisible = ref(false)
const curFormConfig = ref({})
const curFormResult = ref({})
const showDetail = async (data) => {
  const res = await selectPaperResult({ id: data.resultId, formId: props.position.paperId })
  if (res.code === 20000) {
    curFormConfig.value = res.data
    res.data.formItemList.forEach(item => {
      if (!item.modelValue) return
      curFormResult.value[item.formItemId] = item.modelValue
    })
    detailVisible.value = true
  }
}

// 批量通知相关
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

const handleBatchNotice = async () => {
  if (!customize.value.trim()) {
    ElMessage.warning('请先填写通知内容')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认向${selectedRows.value.length}个申请人发送以下通知？\n\n【${props.position.name}】，${customize.value}`,
      '确认发送通知',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const noticeData = {
      customize: customize.value,
      postName: props.position.name,
      recordUserVoList: selectedRows.value.map(row => ({
        account: row.account,
        recordId: row.id,
        userId: row.userId
      })),
      type: 0
    }

    const res = await noticeRecord(noticeData)
    if (res.code === 20000) {
      ElMessage.success('批量通知发送成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('通知发送失败')
    }
  }
}

// 修改审核处理函数
const handleAudit = async (data, isPass) => {
  try {
    let reason = ''
    if (!isPass) {
      // 不通过时弹出输入框
      const { value } = await ElMessageBox.prompt('请输入不通过原因', '填写原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (!value) {
            return '原因不能为空'
          }
          return true
        }
      })
      reason = value
    }

    const res = await updatePaperResultState({
      id: data.resultId,
      state: isPass ? 1 : 2,
      reviewOpinion: reason
    })

    if (res.code === 20000) {
      ElMessage.success('审核成功')
      await getApplicationList()
    } else {
      ElMessage.error('审核失败')
    }
  } catch (err) {
    // 用户取消输入原因
  }
}

onMounted(() => {
  getApplicationList()
})
</script>

<style lang="scss" scoped>
.statistics-container {
  .notice-module {
    background: #f5f7fa;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;

    .template-preview {
      margin-bottom: 15px;

      .title {
        font-weight: bold;
        margin-bottom: 8px;
      }

      .content {
        padding: 10px;
        background: #fff;
        border-radius: 4px;
        border: 1px solid #dcdfe6;
      }
    }
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    justify-content: space-between;

    .filter-section {
      display: flex;
      gap: 10px;
    }
  }
}

.report-iframe-container {
  width: 100%;
  height: 70vh;

  iframe {
    width: 100%;
    height: 100%;
  }
}

::v-deep(.el-dialog .el-dialog__body) {
  padding: 0;
}
</style>
